const { src, dest, series, parallel, watch } = require("gulp");
//src dest解构
const sass = require("gulp-sass");//使用sass
const webserver = require("gulp-webserver");
const webpack = require("webpack-stream");//打包js
const proxy = require("http-proxy-middleware");//解决跨域请求，代理配置

function copyHTML() {
    return src("./src/*.html")
        .pipe(dest('./dev/'));
}

function copyImages() {
    return src('./src/img/*.*')
        .pipe(dest('./dev/img'));
}
function copyLib() {
    return src('./src/lib/*.*')
        .pipe(dest('./dev/js/lib'));
}

function compileCss() {
    return src('./src/style/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(dest("./dev/style/"))
}

function compileJS() {
    return webpack({
        mode: "development",
        entry: './src/app.js',
        devtool: 'source-map',
        output: {
            filename: 'app.min.js'
        },
        module: {
            rules: [
                {
                    test: /\js$/,//匹配所有js
                    exclude: /(node_modules)/,//排除node-modules中的文件
                    use: {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-env'],
                            plugins: ['@babel/plugin-transform-runtime']
                        }
                    }
                },
                {//template渲染页面时用到
                    test: /\.html$/,
                    loader: "string-loader"
                }
            ]
        }
    })
        .pipe(dest('./dev/js/'))
}

function server() {
    return src('./dev/')
        .pipe(webserver({
            livereload: true,//支持热更新
            open: true,  //自动打开页面
            middleware: [
                proxy('./imginfo', {
                    target: "http://localhost:3000",
                    changeOrigin: true //是否允许跨域
                })
            ]
        }))
}

function watchFile() {
    watch('./src/**/*.html', copyHTML);
    watch('./src/**/*.js', compileJS);
    watch('./src/style/*.scss', compileCss);
}
function copyFonts() {
    return src('./src/style/fonts/*.*')
        .pipe(dest('./dev/style/fonts/'));
}

exports.default = series(parallel(compileJS, compileCss, copyHTML, copyImages, copyFonts, copyLib), server, watchFile);